package cn.fang2chen.java.distributed.lock.framework.impl;

import cn.fang2chen.java.distributed.lock.framework.*;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;

/**
 * 分布式互斥锁的实现
 */
public class DistributedMutex implements DistributedLock, DistLockCopyAble {

    private final RemoteLockParam remoteLockParam;
    private final RemoteLockSynchronizer remoteLockSynchronizer;

    private final Sync sync;

    public DistributedMutex(RemoteLockParam remoteLockParam, final RemoteLockSynchronizer remoteLockSynchronizer) {
        this.remoteLockParam = remoteLockParam;
        this.remoteLockSynchronizer = remoteLockSynchronizer;
        sync = new Sync(remoteLockSynchronizer);

    }

    public void lock() {
        sync.acquireDistributed(1, remoteLockParam);
    }

    public boolean tryLock() {
        return sync.tryAcquireDistributed(1, remoteLockParam);
    }

    public boolean tryLock(long timeout, TimeUnit unit)
            throws InterruptedException {
        return sync.tryAcquireNanosDistributed(1, unit.toNanos(timeout), remoteLockParam);
    }

    public void unlock() {
        sync.releaseDistributed(1, remoteLockParam);
    }

    public Condition newCondition() {
        throw new UnsupportedOperationException();
    }

    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptiblyDistributed(1, remoteLockParam);
    }

    public boolean isLocked() {
        return sync.isLocked(remoteLockParam);
    }

    @Override
    public long remainingTime() {
        return sync.remainingTime(remoteLockParam);
    }

    @Override
    public DistributedLock copy(RemoteLockParam remoteLockParam) {
        return new DistributedMutex(remoteLockParam, remoteLockSynchronizer);
    }

    private static class Sync extends AbstractDistributedQueuedSynchronizer {

        private final RemoteLockSynchronizer remoteLockSynchronizer;

        public Sync(RemoteLockSynchronizer remoteLockSynchronizer) {
            this.remoteLockSynchronizer = remoteLockSynchronizer;
        }

        @Override
        protected RemoteLockSynchronizer remoteLockSynchronizer() {
            return this.remoteLockSynchronizer;
        }

        // Reports whether in locked state
        @Override
        protected boolean isHeldExclusively() {
            return getState() == 1;
        }

        // Acquires the lock if state is zero
        @Override
        public boolean tryAcquire(int acquires) {
            assert acquires == 1; // Otherwise unused
            if (compareAndSetState(0, 1)) {
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        // Releases the lock by setting state to zero
        @Override
        protected boolean tryRelease(int releases) {
            assert releases == 1; // Otherwise unused
            if (getState() == 0) throw new IllegalMonitorStateException();
            setExclusiveOwnerThread(null);
            setState(0);
            return true;
        }

    }

}

